package com.pengtu.service.app;

import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.dao.QueryFilter.MatchType;
import com.pengtu.dao.app.AttachmentDao;
import com.pengtu.dao.app.CodeDao;
import com.pengtu.dao.app.MessageInfoDao;
import com.pengtu.entity.app.Attachment;
import com.pengtu.entity.app.Code;
import com.pengtu.entity.app.MessageInfo;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.utils.DateUtils;
import com.pengtu.utils.ExcelHelper;
import com.pengtu.utils.UploadFile;
import com.pengtu.utils.web.Struts2Utils;

/**
 * 
 * 一些系统的manager 操作
 * @author 631wj
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class SystemManager {
	
	@Autowired
	private CodeDao codeDao;
	private AttachmentDao attachmentDao;
	private MessageInfoDao messageInfoDao;

	
	@Autowired
	public void setAttachmentDao(AttachmentDao attachmentDao) {
		this.attachmentDao = attachmentDao;
	}

	// -- 码表管理 Manager --//
	@Transactional(readOnly = true)
	public Code getCode(String id) {
		return codeDao.get(id);
	}
	
	/**
	 * 
	 * getCodeList:
	 * 适用:所有的码表列表
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public List<Code> getCodeList(){
		return codeDao.getAll();
	}
	
	/**
	 * 
	 * getCodeList:
	 * 适用:所有的码表列表
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public Page<Code> getCodeList(final Page<Code> page, final QueryFilter queryFilter){
		return codeDao.findPage(page, queryFilter);
	}
	
	/**
	 * 未标识弃用的码表列表
	 * getAvailableCodeList:
	 * 适用:
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public List<Code> getAvailableCodeList(){ 
		return codeDao.findBy("useFlag", Boolean.TRUE, "category,codeId", "asc,asc");
	}
	
	/**
	 * 
	 * 根据种类查询改种类码表下所有码表
	 * 适用: 
	 * @param category
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public List<Code> getCodeListByCategory(Integer category){
		return codeDao.findBy("category", category);
	}
	
	/**
	 * 
	 * getCodeByCategory:
	 * 根据category 与 codeId 查询对应的Code
	 * @param category
	 * @param codeId
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public Code getCodeByCategory(Integer category,String codeId){
		return codeDao.getCodeByCategory(category, codeId);
	}
	
	public void saveCode(Code entity) {
		codeDao.save(entity);
	}

	/**
	 * 
	 * deleteCode:
	 * 适用:
	 * @param id 
	 * @exception 
	 * @since  1.0.0
	 */
	public void deleteCode(String id) {
		codeDao.delete(id);
	}
	
	// -- 附件管理 Manager --//
	
	@Transactional(readOnly = true)
	public Attachment getAttachment(String id) {
		return attachmentDao.get(id);
	}
	
	/**
	 * 
	 * saveAttachment:
	 * 适用: 保存附件
	 * @param attachment 
	 * @exception 
	 * @since  1.0.0
	 */
	public void saveAttachment(Attachment attachment) {
		 attachmentDao.save(attachment);
	}
	
	public boolean deleteAttachment(String rootPath,String id){
		Attachment attachment = getAttachment(id);
		try {
			boolean isDelete = UploadFile.deleteFile(rootPath,attachment);
			if (isDelete) {
			 attachmentDao.delete(attachment);
			 return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	/**
	 * 
	 * getAttachmentList:
	 * 适用:
	 * @param partId
	 * @param tableName
	 * @param tableId
	 * @param tableField
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Transactional(readOnly = true)
	public List<Attachment> getAttachmentList(String partId, String tableName,
			String tableId, String tableField) {
		return attachmentDao.getAttachmentList(partId, tableName, tableId, tableField);
	}
	
	@Transactional(readOnly = true)
	public List<Attachment> getAttachmentList(QueryFilter fileter){
		return attachmentDao.find(fileter);
	}
	
	/**
	 * 上传文件
	 * uploadFile:
	 * 适用:
	 * @param rootPath
	 * @param attachment
	 * @param tableId
	 * @param tableName
	 * @param tableField
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	 public Attachment uploadFile(String rootPath,Attachment attachment,String tableId,String tableName,String tableField) {
		 attachment.setTableId(tableId);
		 attachment.setTableName(tableName);
		 attachment.setTableField(tableField);
		return uploadFile(rootPath,attachment);
		 
	 }
	 /**
	  * 上传文件
	  * uploadFile:
	  * 适用:
	  * @param rootPath
	  * @param attachment
	  * @return 
	  * @exception 
	  * @since  1.0.0
	  */
    public Attachment uploadFile(String rootPath,Attachment attachment) {
    		// 不是修改附件信息
    	 if(StringUtils.isEmpty(attachment.getId())){
			//保存到服务器端
			UploadFile.processUploadedFile(rootPath,attachment);
			// 上传用户
			attachment.setUploadPerson(SpringSecurityUtils.getCurrentUserName());
    	 }
    	 saveAttachment(attachment);
		return attachment;
	}
    
    @Autowired
	public void setMessageInfoDao(MessageInfoDao messageInfoDao) {
		this.messageInfoDao = messageInfoDao;
	}
	public void saveMessageInfo(MessageInfo messageInfo){
		messageInfoDao.save(messageInfo);
	}
	
	public void deleteMessageInfo(String id, String del){
		messageInfoDao.updateMessageInfo(id,del);
	}
	

	@Transactional(readOnly = true)
	public MessageInfo getMessageInfo(String id) {
    	return messageInfoDao.get(id);
	}
	
	@Transactional(readOnly=true)
	public Page<MessageInfo> getMessageInfos(final  Page<MessageInfo> page,
			final  QueryFilter queryfilter){
		return messageInfoDao.findPage(page, queryfilter);
	}
	
	/**批量保存发送的信息*/
	public void saveMsgInfos(List<String> list, MessageInfo messageInfo,
			Attachment attachmention) {
		Date currentDate = DateUtils.getCurrentDate();
		for(String username:list){
			MessageInfo msg = new MessageInfo();
			msg.setSubject(messageInfo.getSubject());
			msg.setContent(messageInfo.getContent());
			msg.setGrade(messageInfo.getGrade());
			msg.setType(messageInfo.getType());
			msg.setReadFlag("0");
			msg.setReceivedel("0");
			msg.setSenddel("0");
			msg.setRemark(messageInfo.getRemark());
			msg.setReceiveUser(username);
			msg.setSendDate(currentDate);
			msg.setSendUser(SpringSecurityUtils.getCurrentUserName());
			this.saveMessageInfo(msg);
			if (null != attachmention) {
				Attachment attachment = new Attachment();
				attachment.setTableId(msg.getId());
				attachment.setTableField("MessageInfo_attachment");
				attachment.setTableName("MessageInfo");
				attachment.setUpfile(attachmention.getUpfile());
				attachment.setUpfileFileName(attachmention.getUpfileFileName());
				attachment.setUpfileContentType(attachmention.getUpfileContentType());
				this.uploadFile(Struts2Utils.getAppRootPath(),
						attachment);
			}
		}		
	}

	/**根据条件得到信息*/
	public Page<MessageInfo> findMessageInfos(String fontype, String mm,
			String sr, Page<MessageInfo> page, QueryFilter queryFilter) throws ParseException {
		if(fontype != null){
			if(!fontype.toString().equals("")){
			queryFilter.addFilter("type", fontype, MatchType.EQ);}
			}
			if(mm != null){
			if(mm.equals("1"))//今天
			{
				queryFilter.addFilter("sendDate", DateUtils.getTodayDate(),MatchType.GE);
			}
			else if(mm.equals("2"))//昨天
			{
				queryFilter.addFilter("sendDate", DateUtils.getDayUpOrDown(DateUtils.getTodayDate(),-1),MatchType.GE);
				queryFilter.addFilter("sendDate", DateUtils.getTodayDate(),MatchType.LT);
			}
			else if(mm.equals("3"))//更早
			{
				queryFilter.addFilter("sendDate", DateUtils.getDayUpOrDown(DateUtils.getTodayDate(),-1),MatchType.LT);
			}
			}
			if(sr != null){
				if(sr.equals("s")){
					queryFilter.addFilter("sendUser", SpringSecurityUtils.getCurrentUserId(),MatchType.EQ);
					queryFilter.addFilter("senddel", "0",MatchType.EQ);
						}
				else {
			        queryFilter.addFilter("receiveUser", SpringSecurityUtils.getCurrentUserId(),MatchType.EQ);
			        queryFilter.addFilter("receivedel", "0",MatchType.EQ);
				}
			}else {
			    queryFilter.addFilter("receiveUser", SpringSecurityUtils.getCurrentUserId(),MatchType.EQ);
			    queryFilter.addFilter("receivedel", "0",MatchType.EQ);
			}
			return this.getMessageInfos(page, queryFilter);
	}

	/**
	 * 
	 * getNoReadCount:得到没有阅读的记录
	 * 适用: 页面中消息盒子
	 * @exception 
	 * @since  1.0.0
	 */
	public long getNoReadCount(String msgType,
			String userId) {
		return messageInfoDao.getNoReadCount(msgType,userId);
	}
	
	
	/**
	 * 
	 * createIndexByLucene:
	 * 适用:
	 * @param fileClassPath跟路径
	 * @param index存放索引路径
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void createIndexByLucene(String fileClassPath,String index){
		attachmentDao.createIndexByLucene(fileClassPath,index);
	}

	
	/**
	 * 
	 * SearchByLucene:
	 * 适用:
	 * @param index索引查询的目录
	 * @param keyword关键词
	 * @param startDate开始时间  格式为 yyyyMMdd 例 20111120 
	 * @param endDate结束时间   格式为 yyyyMMdd 例 20111120 
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public Collection<Attachment> SearchByLucene(String index, String keyword,String startDate, String endDate) {
		return attachmentDao.SearchByLucene(index,keyword,startDate,endDate);
	}

	public void saveMsgInfos(String[] uIdList, MessageInfo messageInfo,
			Attachment attachmention) {
		Date currentDate = DateUtils.getCurrentDate();
		for(String userId : uIdList){
			MessageInfo msg = new MessageInfo();
			msg.setSubject(messageInfo.getSubject());
			msg.setContent(messageInfo.getContent());
			msg.setGrade(messageInfo.getGrade());
			msg.setType(messageInfo.getType());
			msg.setReadFlag("0");
			msg.setReceivedel("0");
			msg.setSenddel("0");
			msg.setRemark(messageInfo.getRemark());
			msg.setReceiveUser(userId);
			msg.setSendDate(currentDate);
			msg.setSendUser(SpringSecurityUtils.getCurrentUserId());
			this.saveMessageInfo(msg);
			if (null != attachmention) {
				Attachment attachment = new Attachment();
				attachment.setTableId(msg.getId());
				attachment.setTableField("MessageInfo_attachment");
				attachment.setTableName("MessageInfo");
				attachment.setUpfile(attachmention.getUpfile());
				attachment.setUpfileFileName(attachmention.getUpfileFileName());
				attachment.setUpfileContentType(attachmention.getUpfileContentType());
				this.uploadFile(Struts2Utils.getAppRootPath(),
						attachment);
			}
		}		
		
	}

	public Page<Attachment> getAttachmentList(Page<Attachment> page,
			QueryFilter filters) {
		return attachmentDao.findPage(page, filters);
	}

	public WritableWorkbook excelItem(List<Attachment> attachments,String filename,String examplePath) throws Exception {
		ExcelHelper helper = ExcelHelper.getInstance();
		WritableWorkbook wwb = helper.createWritableWorkbook(filename,examplePath);
		SheetExcel(helper, wwb, attachments);
		wwb.write();
		wwb.close();
		return wwb;
	}
	
	private void SheetExcel(ExcelHelper helper, WritableWorkbook wwb,
			List<Attachment> attachments) throws Exception {
		WritableSheet[] sheets = wwb.getSheets();
		WritableSheet sheet0 = sheets[0];
		for(int j = 0;j< attachments.size(); j++){
			Attachment attachment = attachments.get(j);
			sheet0.insertRow(1 + j);
			sheet0 = helper.addCell(sheet0, 0,1+j, j+1);
			String tablename = attachment.getTableName();
			if(StringUtils.equals(tablename, "projectDoc")){
				tablename = "工程档案";
			}
			if(StringUtils.equals(tablename, "application")){
				tablename = "监督申请";
			}
			if(StringUtils.equals(tablename, "laboratory")){
				tablename = "工地实验室";
			}
			if(StringUtils.equals(tablename, "completion")){
				tablename = "交竣工资料(公路)";
			}
			if(StringUtils.equals(tablename, "completionWater")){
				tablename = "交竣工资料(水运)";
			}
			if(StringUtils.equals(tablename, "supervise")){
				tablename = "监督资料";
			}
			sheet0 = helper.addCell(sheet0, 1, 1+j, tablename);
			sheet0 = helper.addCell(sheet0, 2, 1+j, attachment.getTableField());
			sheet0 = helper.addCell(sheet0, 3, 1+j, attachment.getUpfileFileName());
		}
	}

	public List<Attachment> getAttachmentLists(String partId, String tableName,
			String tableField, String upfileFileName) {
		return attachmentDao.getAttachmentLists(partId, tableName, tableField, upfileFileName);
	}
}